#!/usr/bin/perl -w

BEGIN {
	push @INC,"/usr/local/cluster/lib/perl";
}

use strict;
use clutils;

$::ARG_verbose=1;
# exit codes
# 1 - unable to open directory /usr/src/cluster [linuxha incorrectly installed?]
# 2 - drbd is not yet loaded!
# 3 - unable to query drbd version

$::D="/usr/src/cluster";
$::M=-1;
$::M8=-1;
$::KERN=`uname -r`; chomp $::KERN;

if(-f "/lib/modules/$::KERN/kernel/drivers/block/drbd.ko" ||
	-f "/lib/modules/$::KERN/kernel/drivers/block/drbd.o") {
	exit 0;
}

# If we get here we need to compile a drbd module.

opendir(DFD,$::D) or exit 1;
{
my $x;
	while($x=readdir(DFD)) {
		if(-d "$::D/$x" && $x =~ /^drbd-0\.7\.(\d+)$/) {
			if(int($1)>$::M) {
				$::M=int($1);
			}
			next;
		}		
		if(-d "$::D/$x" && $x =~ /^drbd-8\.2\.(\d+)$/) {
			if(int($1)>$::M8) {
				$::M8=int($1);
			}
		}		
	}
	closedir(DFD);
}

logmsg("No DRBD module for kernel version '$::KERN' found!");
if($::M==-1 && $::M8==-1) {
	errmsg("No sources directory for DRBD either in /usr/src/cluster!!",1);
}
$::VERS="";
if($::M8==-1) {
	logmsg("Attempting to build DRBD '0.7.$::M' for kernel '$::KERN' now.");
	$::VERS="0.7.$::M";
} else {
	logmsg("Attempting to build DRBD '8.2.$::M8' for kernel '$::KERN' now.");
	$::VERS="8.2.$::M8";
}

$::code="drbd-$::VERS";
chdir "/usr/src/cluster/$::code/drbd" or exit 4;
`make clean all 2>/dev/null`;
if($?>>8) { 
	errmsg("'make clean all' failed - manual module compilation required",4);
}
chdir "..";
`make tools 2>/dev/null`;
if($?>>8) {
	errmsg("'make tools' failed - manual module compilation required",4);
}
`make install 2>/dev/null`;
if($?>>8) {
	errmsg("'make install' failed - manual module compilation required",4);
}
logmsg("DRBD Module installed successfully.");
exit(0);
